var Rx = require("rxjs");
var operators = require("rxjs/operators");
var SERVER_CONST = require("../server-const");
var express = require("express");
var router = express.Router();
var model = require("../model/chatModel");
var collectionModel = require("../model/collectionModel");
var user = model.user;
var channels = model.channels;
var teams = model.teams;
var channelMembers = model.channelMembers;
var teamMembers = model.teamMembers;
var collectionItem = collectionModel.collectionItem;
var label = collectionModel.label;
var util = require("../server-util/util");
var mongoose = require("mongoose");
const globalVar = require("../server-util/globalVar");
const { padStart } = require("lodash");
var post = model.post;
router.get("/", util.checkAuth, function (req, res, next) {
	res.send("respond with a resource");
});

/**
 * @api {POST} /collection/label/update 更新标签
 */
router.post("/label/update", util.checkAuth, function (req, res, next) {
	var UpdateAt = util.generateNow();
	var LabelId = mongoose.Types.ObjectId(req.body.LabelId);
	var Name = req.body.Name;
	new Rx.Observable((ob) => {
		label
			.update(
				{
					_id: LabelId,
				},
				{
					$set: {
						UpdateAt,
						Name,
					},
				}
			)
			.exec((error, result) => {
				if (error) {
					ob.error(error);
				} else {
					ob.next(result);
				}
				ob.complete();
			});
	}).subscribe(
		(result) => {
			util.res.success({
				res,
				data: result,
			});
		},
		(error) => {
			util.res.error({
				res,
				msg: error,
			});
		}
	);
});

/**
 * @api {POST} /collection/label/delete 删除标签
 */
router.post("/label/delete", util.checkAuth, function (req, res, next) {
	var LabelId = mongoose.Types.ObjectId(req.body.LabelId);
	var CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	new Rx.Observable((ob) => {
		collectionItem
			.deleteMany({
				LabelId,
			})
			.exec((error, result) => {
				if (error) {
					ob.error(error);
				} else {
					ob.next(result);
				}
				ob.complete();
			});
	})
		.pipe(
			operators.concatMap((result) => {
				return new Rx.Observable((ob) => {
					label
						.deleteOne({
							_id: LabelId,
						})
						.exec((error, result) => {
							if (error) {
								ob.error(error);
							} else {
								ob.next(result);
							}
							ob.complete();
						});
				});
			}),
			operators.concatMap((result) => {
				return new Rx.Observable((ob) => {
					label
						.aggregate([
							{
								$match: {
									CreatorId,
								},
							},
						])
						.exec((error, result) => {
							if (error) {
								ob.error(error);
							} else {
								ob.next(result);
							}
							ob.complete();
						});
				});
			})
		)

		.subscribe(
			(result) => {
				util.res.success({
					res,
					data: result,
				});
			},
			(error) => {
				util.res.error({
					res,
					msg: error,
				});
			}
		);
});

//新增一个查询笔记的接口
router.post("/listNote", util.checkAuth, function (req, res, next) {
	var LabelId = req.body.LabelId;
	var w = req.body.w;
	var CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	var Type = req.body.Type;
	let pageNum = parseInt(req.body.pageNum - 1);
	let pageSize = parseInt(req.body.pageSize);
	var params = {
		CreatorId,
		Type,
	};
	if (!!LabelId) {
		params.LabelId = mongoose.Types.ObjectId(LabelId);
	}

	var match = {
		$match: params,
	};

	if (!!w) {
		match.$match["$or"] = [
			{ Content: { $regex: new RegExp(w, "ig") } },
			{ Title: { $regex: new RegExp(w, "ig") } },
		];
	}
	collectionItem
		.aggregate([
			match,
			{
				$sort: {
					CreateAt: -1,
				},
			},
			{
				$group: {
					_id: null,
					data: {
						$push: "$$ROOT",
					},
				},
			},
			{
				$project: {
					count: {
						$size: "$data",
					},
					data: 1,
				},
			},
			{
				$unwind: "$data",
			},
			{
				$skip: pageNum * pageSize,
			},
			{
				$limit: pageSize,
			},
			{
				$group: {
					_id: "",
					data: {
						$push: "$$ROOT",
					},
					count: {
						$first: "$count",
					},
				},
			},

			{
				$project: {
					_id: 0,
					data: "$data.data",
					count: 1,
				},
			},
		])
		.exec((error, result) => {
			if (error) {
				util.res.error({
					res,
					msg: error,
				});
			} else {
				util.res.success({
					res,
					data: result[0],
				});
			}
		});
});

/**
 * 这个接口，涉及消息，先不改了
 * @api {POST} /collection/list 笔记 或者 消息查询 ，被标签关联的
 */
router.post("/list", util.checkAuth, function (req, res, next) {
	//61889ca0d731ed08085f8e18
	var LabelId = req.body.LabelId;
	//616d5c9961196a113abc161f
	var CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	//这个Type在数据库collectionitems中，目前只有笔记用了
	//消息类的收藏，没有存入collectionitems表中
	var Type = req.body.Type;

	let pageNum = parseInt(req.body.page.pageNum - 1);
	let pageSize = parseInt(req.body.page.pageSize);

	let pageParams = {
		$facet: {
			metadata: [
				{
					$count: "total",
				},
				{
					$addFields: {
						pageNum,
						pageSize,
					},
				},
			],
			data: [
				{
					$skip: pageNum * pageSize,
				},
				{
					$limit: pageSize,
				},
			],
		},
	};

	//笔记收藏
	if (Type == globalVar.collectionType.NOTE) {
		new Rx.Observable((ob) => {
			collectionItem
				.aggregate([
					{
						$match: {
							LabelId,
							Type,
							CreatorId,
						},
					},

					{
						$sort: {
							CreateAt: -1,
						},
					},
					{
						...pageParams,
					},
				])
				.exec((error, result) => {
					if (error) {
						ob.error(error);
					} else {
						ob.next(result);
					}
					ob.complete();
				});
		}).subscribe(
			(result) => {
				util.res.success({
					res,
					data: result,
				});
			},
			(error) => {
				util.res.error({
					res,
					msg: error,
				});
			}
		);
	}
	//消息收藏
	else if (Type == globalVar.collectionType.CHAT_MSG) {
		post
			.aggregate([
				{
					$match: {
						"Additional.MsgCollection.collectionArr": {
							$elemMatch: {
								_id: LabelId,
							},
						},
					},
				},

				{
					$lookup: {
						from: "users",
						localField: "UserId",
						foreignField: "_id",
						as: "users",
					},
				},
				{
					$lookup: {
						from: "channels",
						localField: "ChannelId",
						foreignField: "_id",
						as: "channels",
					},
				},

				//关联files表，找出files表里的UserId和上面的$users._id对应
				{
					$lookup: {
						from: "files",
						as: "avatar",
						//这里注意要带$号
						let: {
							uid: "$users._id",
						},
						pipeline: [
							{
								$match: {
									$expr: {
										$in: ["$UserId", "$$uid"],
									},
									//类型为头像
									PostFileType: "avatar",
								},
							},
						],
					},
				},

				{
					$unwind: {
						path: "$users",
					},
				},
				{
					$unwind: {
						path: "$channels",
					},
				},

				//将userid 插入到users里面
				{
					$addFields: {
						"users.userid": "$users._id",
						Username: "$users.Username",
						avatar: "$avatar",
						PostId: "$_id",
					},
				},
				{
					...pageParams,
				},
			])
			.exec((error, result) => {
				if (error) {
					util.res.error({
						res,
						msg: error,
					});
				} else {
					util.res.success({
						res,
						data: result,
					});
				}
			});
	}
});

/**
 * @api {POST} /content/update 更新笔记
 */

router.post("/content/update", util.checkAuth, function (req, res, next) {
	var UpdateAt = util.generateNow();
	var Content = req.body.Content;
	var Title = req.body.Title;
	let id = mongoose.Types.ObjectId(req.body.id);
	var Image = JSON.parse(req.body.Image);
	var Position = req.body.Position;

	collectionItem
		.update(
			{
				_id: id,
			},
			{
				$set: {
					UpdateAt,
					Content,
					Title,
					Image,
					Position,
				},
			},
			{
				upsert: true,
			}
		)
		.exec((error, result) => {
			if (error) {
				util.res.error({
					res,
					msg: error,
				});
			} else {
				util.res.success({
					res,
					data: result._doc,
				});
			}
		});
});
/**
 * @api {POST} /content/add 新增笔记
 */
router.post("/content/add", util.checkAuth, function (req, res, next) {
	var CreateAt = util.generateNow();
	var UpdateAt = CreateAt;
	var OrderNum = 0;
	var CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	var LabelId = mongoose.Types.ObjectId(req.body.LabelId);
	var PostId = mongoose.Types.ObjectId(req.body.PostId);
	var Type = req.body.Type;
	var Content = req.body.Content;
	var Title = req.body.Title;
	var Image = JSON.parse(req.body.Image);
	var Position = req.body.Position;
	new Rx.Observable((ob) => {
		new collectionItem({
			CreateAt,
			UpdateAt,
			OrderNum,
			CreatorId,
			LabelId,
			PostId,
			Type,
			Title,
			Content,
			Image,
			Position,
		}).save((error, result) => {
			if (error) {
				ob.error(error);
			} else {
				ob.next(result);
			}
			ob.complete();
		});
	}).subscribe(
		(result) => {
			util.res.success({
				res,
				data: result._doc,
			});
		},
		(error) => {
			util.res.error({
				res,
				msg: error,
			});
		}
	);
});

/*
	通过CreatorId和PostId查找标签
	这里是关联消息的标签创建者的CreatorId，不是消息的CreatorId
*/

router.get("/label/getByMsg", util.checkAuth, function (req, res, next) {
	//这里是关联消息的标签创建者的CreatorId，不是消息的CreatorId
	let CreatorId = req.query.CreatorId; //这里是字符串
	let PostId = mongoose.Types.ObjectId(req.query.PostId);
	post
		.aggregate([
			{
				$match: {
					_id: PostId,
				},
			},

			{
				$project: {
					_id: 0,
					//这个data是别名，随便取
					data: {
						$filter: {
							//注意这里要带$
							input: "$Additional.MsgCollection",
							//别名：首字母必须小写，把$Additional.MsgCollection当成col
							as: "col",
							cond: {
								$eq: [
									//注意这个$$col要写两个$
									"$$col.Creator._id",
									CreatorId,
								],
							},
						},
					},
				},
			},
			{
				$unwind: "$data",
			},
			{
				$project: {
					collectionArr: "$data.collectionArr",
					CreateAt: "$data.CreateAt",
					Creator: "$data.Creator",
				},
			},
		])
		.exec(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			} else {
				util.res.success({
					res,
					//每个消息，对于同一个人来说，只可能有一个关联标签对象，但标签（collectionArr）可以有多个
					data: result[0],
				});
			}
		});
});
/*
	通过日期范围查询标签
*/

router.get("/label/getByDate", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.query.CreatorId);
	let start = req.query.start;
	let end = req.query.end;

	label
		.aggregate([
			{
				$match: {
					CreatorId,
					CreateAt: {
						$lt: end,
						$gte: start,
					},
				},
			},
		])
		.exec(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			} else {
				util.res.success({
					res,
					data: result,
				});
			}
		});
});

/**
 * @api {GET} /label/get 查询标签
 * @apiParam (label) {String} CreatorId
 * @apiSampleRequest off
 * @apiGroup collection
 */
router.get("/label/get", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.query.CreatorId);
	let skip = req.query.skip;
	let limit = req.query.limit;
	let str = req.query.str;

	let match = {
		$match: {
			CreatorId,
		},
	};

	if (str != null) {
		match = {
			$match: {
				CreatorId,
				Name: {
					$regex: new RegExp(str),
					$options: "i",
				},
			},
		};
	}

	let arr = [
		match,
		{
			$sort: {
				CreateAt: -1,
			},
		},
	];

	if (skip != null && limit != null) {
		arr.push({
			$skip: parseInt(skip),
		});
		arr.push({
			$limit: parseInt(limit),
		});
	}

	label.aggregate([...arr]).exec(function (err, result) {
		if (err) {
			util.res.error({
				res,
				msg: "服务器报错",
			});
		} else {
			util.res.success({
				res,
				data: result,
			});
		}
	});
});
/**
 * @api {POST} /label/add 添加收藏标签
 * @apiParam (label) {String} name
 * @apiParam (label) {String} CreatorId
 * @apiSampleRequest off
 * @apiGroup collection
 */
router.post("/label/add", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let Name = req.body.Name;
	label
		.aggregate([
			{
				$match: {
					Name,
					CreatorId,
				},
			},
		])
		.exec(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			} else {
				if (result.length > 0) {
					util.res.notCorrect({
						res,
						msg: "标签名重复",
					});
				} else {
					new label({
						CreatorId,
						Name,
						CreateAt: new Date().getTime().toString(),
					}).save(function (err, result) {
						util.res.success({
							res,
							data: result,
						});
					});
				}
			}
		});
});
module.exports = router;
